<template>
  <div>
    <q-scroll-area style="overflow: hidden;" class="full-height" ref="scrollTargetRef" :thumb-style="thumbStyle">
      <q-infinite-scroll :offset="100" :scroll-target="$refs.scrollTargetRef" ref="scrollTarget">
        <div style="position: relative">
          <div class="fold flex items-center justify-center" @click="toggleHide">
            <q-icon :name="fold?'iconfont icontubiao-43':'iconfont icontubiao-44'"/>
          </div>
          <div class="wrapper padding-20" style="margin-right: 0">
            <q-btn
              class="btn margin-r-20"
              label="部署"
              color="primary"
              unelevated
              :disable="disableDeploy"
              :loading="deployLoading"
              @click="deploy"/>
<!--            <q-btn-->
<!--              class="btn"-->
<!--              label="重启"-->
<!--              color="primary"-->
<!--              unelevated-->
<!--              :disable="disableDeploy"-->
<!--              :loading="deployLoading"-->
<!--              @click="deploy"/>-->
          </div>
          <div class="row flex overflow-hidden-y top-wrapper" :style="{'height': fold ? '0px':'100%'}">
            <div class="col-lg-6 col-md-12 col-sm-12">
              <div class="flex">
                <div style="width: calc(40% - 24px)" class="wrapper md-margin l-margin">
                  <GatewayDetail :detailInfo="detailInfo"/>
                </div>
                <div style="width: calc(60% - 24px)" class="wrapper md-margin">
                  <LanParams :moduleType="moduleType"
                             :lanInfo="lanInfo"
                             :mobileConf="mobileConf"
                             :detailDriverParams="detailDriverParams"
                             :products="products"
                             @successAll="successLan"/>
                </div>
              </div>
            </div>
            <div class="col-lg-6 col-md-12 col-sm-12">
              <div class="flex">
                <div style="width: calc(40% - 24px)" class="wrapper md-margin l-margin">
                  <NetworkInfo :networkInfo="networkInfo" />
                </div>
                <div style="width: calc(60% - 24px)" class="md-margin l-margin">
                  <IORuntimeInfo :ioInfo="IOInfo" :mem-and-rom="memAndRom" />
                </div>
              </div>
            </div>
          </div>
        </div>
        <div>
          <div class="wrapper no-margin">
            <q-tabs
              v-model="tab"
              shrink stretch dense
              inline-label
              align="left"
              active-color="primary"
              indicator-color="primary"
              style="padding: 10px 20px 0;
           position: relative"
            >
              <q-tab name="driver" label="驱动信息"/>
              <q-tab name="application" label="应用信息"/>
            </q-tabs>
            <div class="margin-l-20 margin-r-20">
              <q-separator />
            </div>
            <q-tab-panels v-model="tab" animated style="height: calc(100% - 67px)" class="scrollbar">
              <q-tab-panel name="driver" style="padding:0" class="full-height">
                <DriverInfoCNC v-if="moduleType === 1"
                               :boxId="boxId"
                               :products="products"
                               :productsCnc="productsCnc"
                               ref="driverInfoCNC"
                               :detailDriverParams="detailDriverParams"
                               :productId="productId"
                               :deviceId="deviceId"
                               :selectDriverInfo="selectDriverInfo"
                               :subDevConfigData="subDevConfigData"
                               :lanInfo="lanInfo"
                               @changeDeviceIds="changeDeviceIds"
                               @successAll="successAll"
                               @changeDriverInfo="changeDriverInfo"
                />

                <DriverInfo v-else-if="moduleType===0"
                            :boxId="boxId"
                            ref="driverInfo"
                            :products="products"
                            :detailDriverParams="detailDriverParams"
                            :productId="productId"
                            :deviceId="deviceId"
                            :selectDriverInfo="selectDriverInfo"
                            :lanInfo="lanInfo"
                            :height="height"
                            @changeDeviceIds="changeDeviceIds"
                            @successAll="successAll"
                            @changeDriverInfo="changeDriverInfo" />
              </q-tab-panel>
              <q-tab-panel name="application" style="padding:0" class="full-height">
                <ApplicationInfo class="padding-t-20" :boxId="boxId" />
              </q-tab-panel>
            </q-tab-panels>
          </div>
        </div>
      </q-infinite-scroll>
    </q-scroll-area>
  </div>
</template>

<script>
import GatewayDetail from './components/plc-detail-components/gateway-detail'
import ApplicationInfo from './components/plc-detail-components/application-info'
import DriverInfo from './components/plc-detail-components/driver-info'
import DriverInfoCNC from './components/detail-components/driver-info'
import LanParams from './components/detail-components/lan-params'
import NetworkInfo from './components/detail-components/network-info'
import IORuntimeInfo from './components/detail-components/io-runtime-info'
import {
  deployUcloud, getBoxDetail,
  getPlcBoxDriverInfo,
  getPlcLanInfo,
  getPlcProducts
} from '../../boot/miot/plc-list'
import moment from 'moment'
import { Dialog } from 'quasar'
import { mapGetters } from 'vuex'
import { getBoxProducts } from '../../boot/miot/list'

export default {
  name: 'plc-detail',
  components: {
    GatewayDetail,
    LanParams,
    DriverInfo,
    DriverInfoCNC,
    ApplicationInfo,
    NetworkInfo,
    IORuntimeInfo
  },
  data () {
    return {
      thumbStyle: this.CommonConfig.thumbStyle,
      tab: 'driver',
      boxId: '',
      productId: '',
      deviceId: [],
      memAndRom: {
        cpuUsage: 0,
        diskUsage: 0,
        memoryUsage: 0,
        cpuUsageWarning: false,
        diskUsageWarning: false,
        memoryUsageWarning: false
      },
      detailInfo: {
        productName: '',
        productSN: '',
        createdTime: '',
        deviceSN: '',
        lastOnlineTime: '',
        lineStatus: '',
        deploymentStatus: '',
        deployedDate: '',
        lastOfflineTime: '',
        cpu: '',
        os: '',
        softwareVersion: ''
      },
      IOInfo: {
      },
      detailDriverParams: {
        ucloudBoxNum: '',
        productId: '',
        gatewayId: '',
        gatewaySN: '',
        productName: '',
        subDeviceId: '',
        boxNum: '',
        driverName: ''
      },
      mobileConf: {
        dns: [],
        mobileApn: '',
        mobileMode: null,
        mobilePassword: '',
        mobileUser: '',
        netPortConf: '',
        watchDog: null
      },
      lanInfo: {
        lan0: {
          dhcp: null,
          gateway: '',
          ipaddr: '',
          netmask: '',
          speed: null,
          carrier: null
        },
        lan1: {
          dhcp: null,
          gateway: '',
          ipaddr: '',
          netmask: '',
          speed: null,
          carrier: null
        }
      },
      networkInfo: {
        state: '',
        iccid: '',
        imei: '',
        imsi: '',
        model: '',
        soft: '',
        rssi: ''
      },
      selectDriverInfo: {
        driver: '',
        version: '',
        driverIp: '',
        driverPort: '',
        driverName: ''
      },
      subDevConfigData: {
        collectIp: '',
        collectPort: '',
        fileIp: '',
        filePort: '',
        fileProtocol: '',
        fileUsername: '',
        filePassword: '',
        dncPort: '',
        dncProtocol: '',
        dncUsername: '',
        dncPassword: '',
        fileDev: '',
        serialPort: '',
        baudRate: '',
        dataBit: '',
        stopBit: '',
        parity: '',
        flowControl: '',
        collectCycle: '',
        collectInterval: ''
      },
      moduleType: null,
      deployLoading: false,
      products: [],
      productsCnc: [],
      fold: false
    }
  },
  computed: {
    ...mapGetters([
      'client'
    ]),
    height () {
      return this.fold ? '420px' : '300px'
    },
    disableDeploy () {
      // 如果是A11的盒子,只需配置驱动
      if (this.detailInfo.productName === 'Horseman-A11') {
        return !this.selectDriverInfo?.driverName
      }
      return !this.mobileConf?.netPortConf || !this.selectDriverInfo?.driverName
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      const { boxId, deviceId, deployedDate, moduleType, boxNum } = vm.$route.query
      vm.boxId = boxId
      vm.productId = boxNum
      vm.moduleType = moduleType ? Number(moduleType) : 0
      vm.detailInfo.deployedDate = deployedDate
      vm.detailDriverParams.ucloudBoxNum = boxId
      vm.detailDriverParams.boxNum = boxNum
      try {
        vm.deviceId = JSON.parse(deviceId)
      } catch (e) {
        vm.deviceId = []
      }
      vm.init()
    })
  },
  methods: {
    init () {
      this.getPlcBoxDriverInfoData()
      this.getPlcLanInfo()
      if (this.moduleType === 1) {
        this.getBoxProducts()
        // this.getPlcProductInfo()
      } else if (this.moduleType === 0) {
        this.getPlcProductInfo()
      }
      this.getBoxDetailInfo()
    },
    async getBoxDetailInfo () {
      if (this.client && this.client.connected) {
        await getBoxDetail(this.boxId)
        const subscribe = this.client.subscribe(
          `/topic/moses/monitor/gatewayDetail/${this.boxId}`,
          (message) => {
            try {
              subscribe.unsubscribe()
              const ret = JSON.parse(message.body)
              if (ret.code === '1200') {
                const data = JSON.parse(ret.data)
                this.IOInfo = data.IO
                const lan = data.Lan
                if (lan && lan[0]) {
                  this.lanInfo.lan0.carrier = lan[0].state?.carrier
                }
                if (lan && lan[1]) {
                  this.lanInfo.lan1.carrier = lan[1].state?.carrier
                }
                const state = data.Mobile.state
                this.networkInfo.state = state.state
                this.networkInfo.iccid = state.iccid
                this.networkInfo.imei = state.imei
                this.networkInfo.imsi = state.imsi
                this.networkInfo.model = state.model
                this.networkInfo.soft = state.soft
                this.networkInfo.rssi = state.rssi
              }
            } catch (e) {
            }
          })
      } else {
        setTimeout(() => {
          this.getBoxDetailInfo()
        }, 1000)
      }
    },
    async getBoxProducts () {
      const { data } = await getBoxProducts()
      if (data && data.products) {
        this.productsCnc = data.products
      }
    },
    // 获取产品列表
    async getPlcProductInfo () {
      const { data } = await getPlcProducts()
      if (data?.length) {
        this.products = data
      }
    },
    getPlcBoxDriverInfoData () {
      getPlcBoxDriverInfo(this.boxId).then(res => {
        const data = res.data
        this.detailInfo.createdTime = data.createdTime ? moment(Number(data.createdTime)).format('YYYY-MM-DD') : ''
        this.detailInfo.lastOnlineTime = data.lastOnlineTime ? moment(Number(data.lastOnlineTime)).format('YYYY-MM-DD HH:mm:ss') : ''
        this.detailInfo.lastOfflineTime = data.lastOfflineTime ? moment(Number(data.lastOfflineTime)).format('YYYY-MM-DD HH:mm:ss') : ''
        this.detailInfo.productName = data.productName
        this.detailInfo.cpu = data.cpu
        this.detailInfo.os = data.os
        this.detailInfo.softwareVersion = data.softwareVersion
        this.detailInfo.productSN = data.productSN
        this.detailInfo.deviceSN = data.deviceSN
        this.detailInfo.lineStatus = data.lineStatus
        this.detailInfo.deploymentStatus = data.deploymentStatus
        this.detailDriverParams.productId = data.productId
        this.detailDriverParams.productName = data.productName
        this.detailDriverParams.driverName = data.driverName + '_' + data.version
        this.detailDriverParams.gatewayId = data.gatewayId
        this.detailDriverParams.subDeviceId = data.subDeviceId
        this.detailDriverParams.gatewaySN = data.deviceSN
        // cpu使用率
        const cpuUsage = Number(data.cpuUsage)
        // 磁盘使用率
        const diskUsage = Number(data.diskUsage)
        // 内存使用率
        const memoryUsage = Number(data.memoryUsage)
        if (!isNaN(cpuUsage)) {
          this.memAndRom.cpuUsage = Number((cpuUsage / 100).toFixed(2))
          this.memAndRom.cpuUsageWarning = cpuUsage >= 80
        }
        if (!isNaN(diskUsage)) {
          this.memAndRom.diskUsage = Number((diskUsage / 100).toFixed(2))
          this.memAndRom.diskUsageWarning = diskUsage >= 80
        }
        if (!isNaN(memoryUsage)) {
          this.memAndRom.memoryUsage = Number((memoryUsage / 100).toFixed(2))
          this.memAndRom.memoryUsageWarning = memoryUsage >= 80
        }
      })
    },
    // 获取lanInfo的详情信息
    getPlcLanInfo () {
      getPlcLanInfo(this.boxId).then(res => {
        if (res.data && res.data[0] && Object.keys(res.data[0]).length > 0) {
          const lanInfo = res.data[0]
          this.lanInfo.lan0.dhcp = lanInfo.lan0.dhcp
          this.lanInfo.lan0.gateway = lanInfo.lan0.gateway
          this.lanInfo.lan0.ipaddr = lanInfo.lan0.ipaddr
          this.lanInfo.lan0.netmask = lanInfo.lan0.netmask
          this.lanInfo.lan0.speed = lanInfo.lan0.speed
          this.lanInfo.lan1.dhcp = lanInfo.lan1.dhcp
          this.lanInfo.lan1.gateway = lanInfo.lan1.gateway
          this.lanInfo.lan1.ipaddr = lanInfo.lan1.ipaddr
          this.lanInfo.lan1.netmask = lanInfo.lan1.netmask
          this.lanInfo.lan1.speed = lanInfo.lan1.speed
          this.mobileConf = res.data[1]?.mobileConf
        } else {
          Object.assign(this.lanInfo, this.$options.data.call(this).lanInfo)
          Object.assign(this.mobileConf, this.$options.data.call(this).mobileConf)
        }
      })
    },
    changeDriverInfo (data) {
      if (!data) {
        this.selectDriverInfo = {}
        return
      }
      this.driverInfo = data
      this.detailDriverParams.gatewayId = data.gatewayId
      this.selectDriverInfo = {
        driver: data.driverId,
        version: data.version,
        driverIp: data.driverIp,
        driverPort: data.driverPort,
        driverName: data.driverName + '_' + data.version,
        device: data?.deviceListResVos ? data?.deviceListResVos[0]?.assetNumber : null
      }
      // 如果是cnc设备设置
      if (this.moduleType === 1) {
        const subDevConfigData = {
          collectIp: data.collectIp,
          collectPort: data.collectPort,
          fileIp: data.fileIp,
          filePort: data.filePort,
          fileProtocol: data.fileProtocol,
          fileUsername: data.fileUsername,
          filePassword: data.filePassword,
          dncPort: data.dncPort,
          dncProtocol: data.dncProtocol,
          dncUsername: data.dncUsername,
          dncPassword: data.dncPassword,
          fileDev: data.fileDev,
          serialPort: data.serialPort,
          baudRate: data.baudRate,
          dataBit: data.dataBit,
          stopBit: data.stopBit,
          parity: data.parity,
          flowControl: data.flowControl,
          collectCycle: data.collectCycle,
          collectInterval: data.collectInterval
        }
        this.subDevConfigData = subDevConfigData
      }
    },
    // deviceId改变
    changeDeviceIds (data) {
      this.deviceId = data
    },
    // 更改lan成功
    successLan () {
      this.getPlcLanInfo()
    },
    // 全部成功
    successAll () {
      const query = {
        ...this.$route.query,
        deviceId: JSON.stringify(this.deviceId)
      }
      this.getPlcLanInfo()
      if (this.moduleType === 0) {
        this.$refs.driverInfo.getPlcBindDriverInfo()
      } else if (this.moduleType === 1) {
        this.$refs.driverInfoCNC.getPlcBindDriverInfo()
      }
      this.$router.replace({ name: 'plcDetail', query: query })
    },
    async deploy () {
      const params = {
        gatewayId: this.detailDriverParams.gatewayId,
        moduleType: this.moduleType,
        productId: this.detailDriverParams.productId,
        ucloudBoxNum: this.detailDriverParams.ucloudBoxNum,
        boxId: this.detailDriverParams.boxNum
      }
      this.deployLoading = true
      try {
        await deployUcloud(params)
        this.$message.success('部署命令已提交')
      } catch (e) {
      } finally {
        this.deployLoading = false
      }
    },
    /**
     * 检查盒子是否在线
     */
    checkOnline () {
      return new Promise((resolve, reject) => {
        if (this.client && this.client.connected) {
          const subscribe = this.client.subscribe(
            `/topic/deploy/newBox/${this.detailDriverParams.ucloudBoxNum}`,
            (message) => {
              try {
                subscribe.unsubscribe()
                const ret = JSON.parse(message.body)
                if (ret && ret.data && ret.data.status === 'success') {
                  resolve()
                } else {
                  Dialog.create({
                    title: `<p class="dialog-notice-title">
                <i class="iconfont icontubiao-28" ></i>部署失败,请重试</p>`,
                    html: true,
                    ok: {
                      unelevated: true,
                      label: '确认'
                    }
                  })
                  reject()
                }
              } catch (e) {
                console.log('解析socket内存报警错误' + e)
                reject()
              }
            }
          )
        } else {
          Dialog.create({
            title: `<p class="dialog-notice-title">
                <i class="iconfont icontubiao-28" ></i>websocket断开连接啦~请稍后重试</p>`,
            html: true,
            ok: {
              unelevated: true,
              label: '确认'
            }
          })
          reject()
        }
      })
    },

    toggleHide () {
      this.fold = !this.fold
    }
  }
}
</script>

<style scoped lang="stylus">
.wrapper
  background #ffffff
  border-radius 6px
  margin-right 24px
  margin-bottom 24px

.fold {
  border-radius: 0px 0px 12px 12px;
  cursor: pointer;
  height: 12px;
  position: absolute;
  width: 80px;
  bottom: 12px;
  left: calc(50% - 105px);
  background: #ffffff;

  .q-icon {
    transform: rotate(90deg)
  }
}

@media (min-width: 1440px)
  .no-margin
    margin-right 0

@media (max-width: 1440px)
  .md-margin
    margin-right 0

@media (min-width: 1040px) and (max-width: 1440px)
  .l-margin
    margin-right 20px
</style>

<style lang="stylus">
.btn
  padding 0
  min-width 96px
  min-height 32px
  line-height: 1
  font-size 14px
  height 32px

.title
  line-height 1
  font-size 16px
  font-weight 500
  color $primary
  margin-bottom 16px
</style>
